package com.olmarket.core.controller;

import com.olmarket.core.api.CommonResult;
import com.olmarket.core.api.ResultCode;
import com.olmarket.core.dto.UserInfoResult;
import com.olmarket.core.dto.UserLoginParams;
import com.olmarket.core.dto.UserModifyPwdParams;
import com.olmarket.core.dto.UserSignupParams;
import com.olmarket.core.entity.User;
import com.olmarket.core.entity.UserStudent;
import com.olmarket.core.service.PermissionService;
import com.olmarket.core.service.UserLoginService;
import com.olmarket.core.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.HashMap;
import java.util.Map;


/**
 * @author h'zh
 * @date: 12.14
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserLoginController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserLoginController.class);
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private UserService userService;
    @Autowired
    PermissionService permissionService;

    @ApiOperation(value = "处理用户登录", notes = "处理三种不同身份用户的登录请求")
    @RequestMapping("/login")
    public CommonResult login(@RequestBody UserLoginParams user) {
        String username = user.getUsername();
        String password = user.getPassword();
        int usertype = user.getUserType();
        Map<String, String> ret = new HashMap<>();
        ret.put("token", userService.login(username, password, usertype));
        return CommonResult.success(ret);
    }

    @RequestMapping("/logout")
    public CommonResult logout() {
        // TODO：在服务端加上 黑名单处理登出的token(redis实现高效)
        // 目前：无为而治，客户端忘记这个token
        return CommonResult.success(null);
    }

    // 实现 get user info
    // 获取已经认证的用户信息
    @ApiOperation("获取当前登陆的用户信息")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<UserInfoResult> getUserInfo(Principal principal) {
        if (null == principal) {
            return CommonResult.unauthorized(null);
        }
        String username = principal.getName();
        User user = userService.getUserByUsername(username);
        UserInfoResult result = new UserInfoResult();
        result.setUsername(user.getUsername());
        result.setUserType(user.getUserType());
        result.setMenus(permissionService.getAccessUrlsOfUser(user));
        return CommonResult.success(result);
    }

    //2021.7.28
    //用户提交的表单中应该有新密码和旧密码
    //增加修改密码的参数集合
    @ApiOperation(value = "修改密码", notes = "用户提交表单修改旧密码为新密码")
    @PostMapping("/modifyPwd")
    public CommonResult<String> modifyPwd(@RequestBody UserModifyPwdParams user) {
        String username = user.getUsername();
        String oldPassword = user.getOldPassword();
        String newPassword = user.getNewPassword();
        int usertype = user.getUserType();

        System.out.println(user);

        User dbUser = userLoginService.getUser(username, oldPassword, usertype);
        if (dbUser == null) {
            return CommonResult.failed(ResultCode.USER_NOT_EXIST);
        }

        System.out.println(dbUser);

        boolean operate = userLoginService.updateUserPassword(dbUser.getUserid(), newPassword);
        return operate ? CommonResult.success("success") : CommonResult.failed("failed");
    }

    //TODO: 处理用户注册
    @ApiOperation(value = "处理用户注册", notes = "用createUser函数")
    @RequestMapping("/signup")
    public CommonResult signup(@RequestBody UserSignupParams userSignupParams) {
        int i = userService.createUser(
                userSignupParams.getUsername(),
                userSignupParams.getPassword(),
                userSignupParams.getUserType()
        );
        if(i>0){
            User user = userService.getUserByUsername(userSignupParams.getUsername());
            System.out.println(user);
            int j = userService.createStudent(
                    user.getUserid(),
                    userSignupParams.getName(),
                    userSignupParams.isSex(),
                    userSignupParams.getAddress(),
                    userSignupParams.getQq(),
                    userSignupParams.getTel()
            );
            System.out.println("\nUserLoginController j= " + j);
            return j>0 ? CommonResult.success("success") : CommonResult.failed("failed");
        }
        return CommonResult.failed("failed");
    }
}



